package com.coolweather.android;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {
    private static final int LEVEL_PROVINCE=0;
    private static final int LEVEL_CITY=1;
    private static final int LEVEL_COUNTY=2;
    private ProgressDialog progressDialog;
    private TextView titleText;
    public Button btn5;
    public ListView listView;
    private ArrayAdapter<String> adapter;
    private List<String> dataList=new ArrayList<>();
    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;
    private  Province selectedProvince;
    private  City selectedCity;
    private County selectedCounty;
    private int currentLevel;
    public ImageView backimage;
    ListView list;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
        View view=inflater.inflate(R.layout.activity_find,container,false);
        titleText=(TextView) view.findViewById(R.id.title_text);

         btn5=(Button) view.findViewById(R.id.button2);
        backimage=(ImageView) view.findViewById(R.id.back_image);

        listView=(ListView)  view.findViewById(R.id.list_view);
        adapter=new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1,dataList);
        listView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if(currentLevel==LEVEL_PROVINCE){
                    selectedProvince =provinceList.get(position);
                    int provinceCode=selectedProvince.getProvinceCode();
                    displayCityData();
                }else if(currentLevel==LEVEL_CITY) {
                    Log.d("level", "enter cityLevel");
                    selectedCity = cityList.get(position);
                    int cityCode = selectedCity.getCityCode();
                    displayCountyData();

                }else if (currentLevel == LEVEL_COUNTY) {//是县
                    String weatherId = countyList.get(position).getWeatherId();
                    if (getActivity() instanceof MainActivity2) {//在滑动窗口界面，则不变，重新选择城市
                        Intent intent = new Intent(getActivity(), WeatherActivity2.class);//启动WeatherActivity
                        intent.putExtra("weather_id", weatherId);//传值P50
                        startActivity(intent);
                        getActivity().finish();
                    } else if (getActivity() instanceof WeatherActivity2) {//在WeatherActivity活动中
                        WeatherActivity2 activity = (WeatherActivity2) getActivity();
                        activity.drawerLayout.closeDrawers();//关闭滑动菜单
                        activity.swipeRefresh.setRefreshing(true);//下拉刷新进度条
                        activity.requestWeather(weatherId);
                    }
                }}
        });


        backimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(currentLevel==LEVEL_COUNTY){
                    displayCityData();
                }else if(currentLevel==LEVEL_CITY){
                    displayProvinceData();
                }

            }
        });


        createBase();
//        DataSupport.deleteAll(Province.class);
//        DataSupport.deleteAll(City.class);
//        DataSupport.deleteAll(County.class);
        displayProvinceData();

        btn5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                displayProvinceData();
             /*
                if(view.getId()==R.id.button2){
                    sendRequestWithOkHttp();

                }
            }
            private void sendRequestWithOkHttp(){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            OkHttpClient client=new OkHttpClient();
                            Request request=new Request.Builder()
                                    .url("http://guolin.tech/api/china")
                                    .build();
                            Response response=client.newCall(request).execute();
                            String responseData=response.body().string();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }).start();

              */
            }
        });
    }
    private  void getDataThread(String address,String type){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client=new OkHttpClient();
                    Request request=new Request.Builder()
                            .url(address)
                            .build();
                    Response response=client.newCall(request).execute();
                    String responseData=response.body().string();
                    if("province".equals(type)){
                        parseProvinceData(responseData);

                    }else if("city".equals(type)){
                        parseCityData(responseData);
                    }else if("county".equals(type)){
                        parseCountyData(responseData);
                    }

                    Log.d("info",responseData);
                }catch (IOException | JSONException e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private  void parseProvinceData(String data) throws JSONException {
        JSONArray allProvinces = new JSONArray(data);
        for (int i = 0; i < allProvinces.length(); i++) {
            JSONObject provinceObject = allProvinces.getJSONObject(i);
            String provinceName = provinceObject.getString("name");
            int provinceCode = provinceObject.getInt("id");
            Province db=new Province();
            db.setProvinceName(provinceName);
            db.setProvinceCode(provinceCode);
            db.save();
            Log.d("info", provinceName);


        }
    }
    private  void displayProvinceData(){
        backimage.setVisibility(View.GONE);
        provinceList= DataSupport.findAll(Province.class);
        if(provinceList.size()>0){
            dataList.clear();
            for(Province province:provinceList){
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();
            currentLevel=LEVEL_PROVINCE;
        }else {
            String url="http://localhost:8080/cool/ProvinceTest";
            //String url="http://guolin.tech/api/china";
            getDataThread(url,"province");
        }
    }
    private  void createBase(){
        Connector.getDatabase();
    }
    private void parseCityData(String data) throws JSONException {
        JSONArray allCity = new JSONArray(data);
        int provinceCode = selectedProvince.getProvinceCode();
        for (int i = 0; i < allCity.length(); i++) {
            JSONObject cityObject = allCity.getJSONObject(i);
            String cityName = cityObject.getString("name");
            int cityCode = cityObject.getInt("id");
            City db = new City();
            db.setCityName(cityName);
            db.setProvinceId(provinceCode);
            db.setCityCode(cityCode);
            db.setId(cityCode);
            db.save();

        }
    }

    private  void displayCityData(){
        int provinceCode = selectedProvince.getProvinceCode();
        backimage.setVisibility(View.VISIBLE);
        cityList=DataSupport.where("provinceId=?",String.valueOf(provinceCode)).find(City.class);
        cityList= DataSupport.findAll(City.class);
        if(cityList.size()>0){
            dataList.clear();
            for(City city:cityList){
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            currentLevel=LEVEL_CITY;
        }else {
            String url="http://localhost:8080/cool/CityTest"+provinceCode;
            //String url="http://guolin.tech/api/china"+provinceCode;
            getDataThread(url,"city");
        }
    }

    private void parseCountyData(String data) throws JSONException {
        JSONArray allCounty = new JSONArray(data);
        int cityCode = selectedCity.getCityCode();
        for (int i = 0; i < allCounty.length(); i++) {
            JSONObject countyObject = allCounty.getJSONObject(i);
            String countyName = countyObject.getString("name");
            int countyCode = countyObject.getInt("id");
            String weatherId=countyObject.getString("weather_id");
            County db = new County();
            db.setCountyName(countyName);
            db.setCityId(cityCode);
            db.setId(countyCode);
            db.setWeatherId(weatherId);
            db.save();

        }
    }

    private  void displayCountyData(){
        int cityCode = selectedCity.getCityCode();
        backimage.setVisibility(View.VISIBLE);
        countyList=DataSupport.where("cityId=?",String.valueOf(cityCode)).find(County.class);
        if(countyList.size()>0){
            dataList.clear();
            for(County county:countyList){
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            currentLevel=LEVEL_COUNTY;
        }else {
            int provinceCode = selectedProvince.getProvinceCode();
            String url="http://localhost:8080/cool/CountyTest"+provinceCode+"/"+cityCode;
            getDataThread(url,"county");
        }
    }



}



